package cn.mjnxin.iot.client.base;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.mjnxin.iot.base.util.EngineClassLoader;
import cn.mjnxin.iot.connector.handle.IHandleFactory;
import cn.mjnxin.iot.connector.message.IMessage;
import cn.mjnxin.iot.connector.message.IMessageHandle;

/**
 * 加载线程的报文定制包.<br/>
 *
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class TerminalMessageHandleLoader {
	private static final Logger LOGGER = LoggerFactory.getLogger(TerminalMessageHandleLoader.class);

	/**
	 * 导入目录里面的所有jar包.<br/>
	 * 
	 * @param factory
	 * @param path
	 */
	public static void findAndLoad(IHandleFactory factory, String path) {
		File jarpath = new File(path);
		if (!jarpath.isDirectory()) {
			return;
		}

		for (File jarFile : jarpath.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				String filename = pathname.getName();
				if (filename.endsWith(".jar") || filename.endsWith(".zip")) {
					return true;
				}

				return false;
			}
		})) {
			Class<?> clazz = loadExistJar(jarFile, IMessageHandle.class);
			if (clazz != null) {
				try {
					@SuppressWarnings("unchecked")
					IMessageHandle<? extends IMessage<?>> returnClazz = (IMessageHandle<? extends IMessage<?>>) clazz.newInstance();
					factory.registMessageHandle(returnClazz);
				} catch (Exception e) {
					System.out.println("类[" + clazz + "]初始化失败！");
					LOGGER.error(e.getMessage(), e);
				}
			}
		}
	}

	public static Class<?> loadExistJar(File jarFile, Class<?> superClass) {
		Class<?> returnClazz = null;
		java.util.jar.JarFile jarfile = null;
		try {
			jarfile = new JarFile(jarFile);
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
			return null;
		}
		Enumeration<JarEntry> entrys = jarfile.entries();
		EngineClassLoader classLoader = new EngineClassLoader();
		try {
			classLoader.addURL(jarFile.toURI().toURL());
		} catch (MalformedURLException e) {
			LOGGER.error(e.getMessage(), e);
			try {
				jarfile.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				classLoader.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return null;
		}

		while (entrys.hasMoreElements()) {
			JarEntry jarEntry = entrys.nextElement();
			String entryName = jarEntry.getName();
			if (entryName.endsWith(".class")) {
				if (entryName.indexOf("$") > 0) {
					// 不加载内部类
					continue;
				}
				entryName = entryName.replaceAll("/", ".");
				try {
					Class<?> object = classLoader.loadClass(entryName.substring(0, entryName.length() - 6));

					// 判断是否有指定类型
					if (superClass.isAssignableFrom(object)) {
						returnClazz = object;
					}
				} catch (Exception e) {
					LOGGER.error(e.getMessage(), e);
				}
			}
		}

		try {
			jarfile.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			classLoader.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return returnClazz;
	}
}
